<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>设备管理</title>
    <jsp:include page="../inc/css.jsp"/>

    <style type="text/css">
        .dataHeadDiv {
            font-size: large;
            font-weight: bold;
        }

        .dataBodyDiv {
            font-size: large;
            line-height: 35px;
        }

        .codeCheckbox {
            zoom: 140%;
            margin-right: 2px;
            vertical-align: middle;
        }

        .codeSpan {
            margin-right: 5px;
            line-height: 35px;
            cursor: pointer;
        }

        .batch_table {
            text-align: center;
            width: 100%;
            border: 1px solid #dee2e6;
            border-collapse: collapse;
            border-spacing: 0;
            border-radius: 10px;
        }

        .batch_table th {
            border: 1px solid #dee2e6;
        }

        .batch_table td {
            border: 1px solid #dee2e6;
        }

        .batch_table input {
            width: 100%;
            border: 0;
            outline: none;
            background-color: rgba(0, 0, 0, 0);
            text-align: center;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="../inc/menu.jsp"/>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card" style="margin-top: 10px">
                        <div class="card-header">
                            <h4>${device.company.name} - ${device.name}</h4>

                            <button type="button" title="返回设备列表" class="btn btn-warning" onclick="_deviceDataList.fn.goBack()" style="margin-right: 5px;">返回</button>

                            <c:if test="${sessionScope.session_master_id == 1}">
                                <button type="button" title="批量修改状态" class="btn btn-primary" onclick="_deviceDataList.fn.batchUpdateStatus()">批量修改状态</button>
                                <button type="button" title="修改因子排放量" class="btn btn-info" onclick="_deviceDataList.fn.updateStaticCode()">修改因子排放量</button>
                            </c:if>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header dataHeadDiv">
                            实时数据（<span id="timeDataTime"></span>）：
                        </div>
                        <div class="card-body dataBodyDiv" id="timeDataDiv"></div>
                        <div class="card-footer" id="timeDataFooterDiv" style="display: none;"></div>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header dataHeadDiv">
                            分钟数据（<span id="minuteDataTime"></span>）：
                        </div>
                        <div class="card-body dataBodyDiv" id="minuteDataDiv"></div>
                        <div class="card-footer" id="minuteDataFooterDiv" style="display: none;"></div>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header dataHeadDiv">
                            小时数据（<span id="hourDataTime"></span>）：
                        </div>
                        <div class="card-body dataBodyDiv" id="hourDataDiv"></div>
                        <div class="card-footer" id="hourDataFooterDiv" style="display: none;"></div>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header dataHeadDiv">
                            日均数据（<span id="dayDataTime"></span>）：
                        </div>
                        <div class="card-body dataBodyDiv" id="dayDataDiv"></div>
                        <div class="card-footer" id="dayDataFooterDiv" style="display: none;"></div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<div class="modal inModal fade" id="codeInfoModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">设备字段编辑</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <input type="hidden" id="hiddenCodeInfoDeviceCode"/>
                    <input type="hidden" id="hiddenCodeInfoType"/>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">内容：</label>

                        <div class="col-8">
                            <input type="text" id="codeInfoText" maxlength="30" class="form-control" style="width: 95%"/>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="_deviceDataList.fn.saveCodeInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal inModal fade" id="codeDictBatchModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">批量修改设备参数状态</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <form role="form" class="form-group">
                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">参数类型：</label>

                        <div class="col-8">
                            <select id="codeDictTypeList" class="form-control" style="width: 95%">
                                <option value="Rtd">实时值</option>
                                <option value="Min">最小值</option>
                                <option value="Max">最大值</option>
                                <option value="Avg">平均值</option>
                                <option value="Cou">累计值</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-inline" style="margin-bottom: 10px;">
                        <label class="col-4">参数状态：</label>

                        <div class="col-8">
                            <select id="codeDictStatusList" class="form-control" style="width: 95%">
                                <option value="1">显示</option>
                                <option value="0">隐藏</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="_deviceDataList.fn.batchSaveStatus()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal inModal fade" id="updateStaticCodeModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">修改设备汇总参数</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <table class="batch_table">
                    <tr id="batchAddTBody">
                        <th>排放因子名称</th>
                        <th>年排放总量</th>
                        <th>计算周期（天）</th>
                        <th>操作</th>
                    </tr>
                    <tr>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info" onclick="_deviceDataList.fn.addNewLine('', 0, 365)">添加一行</button>
                <button type="button" class="btn btn-primary" onclick="_deviceDataList.fn.saveEmissionInfo()">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<input id="hiddenDeviceId" type="hidden" value="${device.id}"/>
<input id="hiddenDeviceCode" type="hidden" value="${device.code}"/>

<!-- page script -->
<script type="text/javascript">
    let _deviceDataList = {
        v: {
            list: [],
            tempCodeDict: '',
            tempDeviceCode: '',
            tempCodeDictCode: '',
            tempType: 2011
        },
        fn: {
            init: function () {
                let loginMasterId = $('#loginMasterId').val();

                if (loginMasterId === '1') {
                    $('#timeDataFooterDiv').css('display', '');
                    $('#minuteDataFooterDiv').css('display', '');
                    $('#hourDataFooterDiv').css('display', '');
                    $('#dayDataFooterDiv').css('display', '');
                }

                // 加载最新一条实时数据
                _deviceDataList.fn.getDataList(2011);
                _deviceDataList.fn.getDataList(2051);
                _deviceDataList.fn.getDataList(2061);
                _deviceDataList.fn.getDataList(2031);

                _deviceDataList.fn.loadDeviceEmissionInfo();
            },
            goBack: function () {
                window.history.go(-1);
            },
            getDataList: function (type) {
                $.post('backend/device/getInfo', {
                    deviceCode: $('#hiddenDeviceCode').val(),
                    type: type
                }, function (result) {
                    let content = '';
                    let timeStr = '';
                    let footerContent = '';

                    if (null != result && result.valueList.length > 0) {
                        timeStr = crtTimeFtt(result.recordTime);

                        $.each(result.valueList, function (i, item) {
                            content += item.code + '-' + item.name + '：' + item.value + '<span style="visibility: hidden">分</span>';

                            // 时间不允许修改
                            if (item.code === 'CP_DataTime') {
                                footerContent += '<input class="codeCheckbox" type="checkbox" onclick="return false;" checked value="' + item.code + '" /><span class="codeSpan" style="cursor: default;" title="时间">时间</span><span style="visibility: hidden">分</span>';
                            } else {
                                if (item.status === 1) {
                                    footerContent += '<input class="codeCheckbox" type="checkbox" onchange="_deviceDataList.fn.changeDeviceDataStatus(\'' + result.device.code + '\',' + result.type + ',this)" checked value="' + item.code + '" /><span class="codeSpan" title="点击切换显示状态" onclick="_deviceDataList.fn.changeCodeText(\'' + result.device.code + '\',' + result.type + ',this)">' + item.name + '</span><span style="visibility: hidden">分</span>';
                                } else {
                                    footerContent += '<input class="codeCheckbox" type="checkbox" onchange="_deviceDataList.fn.changeDeviceDataStatus(\'' + result.device.code + '\',' + result.type + ',this)" value="' + item.code + '" /><span class="codeSpan" title="点击切换显示状态" onclick="_deviceDataList.fn.changeCodeText(\'' + result.device.code + '\',' + result.type + ',this)">' + item.name + '</span><span style="visibility: hidden">分</span>';
                                }
                            }
                        });
                    }

                    if (type === 2011) {
                        $('#timeDataTime').html(timeStr);
                        $('#timeDataDiv').html(content);
                        $('#timeDataFooterDiv').html(footerContent);
                    } else if (type === 2051) {
                        $('#minuteDataTime').html(timeStr);
                        $('#minuteDataDiv').html(content);
                        $('#minuteDataFooterDiv').html(footerContent);
                    } else if (type === 2061) {
                        $('#hourDataTime').html(timeStr);
                        $('#hourDataDiv').html(content);
                        $('#hourDataFooterDiv').html(footerContent);
                    } else {
                        $('#dayDataTime').html(timeStr);
                        $('#dayDataDiv').html(content);
                        $('#dayDataFooterDiv').html(footerContent);
                    }
                });
            },
            batchUpdateStatus: function () {
                $('#deviceShareIp').val('');
                $('#deviceSharePort').val('');

                $("#codeDictBatchModal").modal("show");
            },
            batchSaveStatus: function () {
                startLoading();

                $.post('backend/data/batchUpdateStatus', {
                    deviceCode: $('#hiddenDeviceCode').val(),
                    type: $('#codeDictTypeList').val(),
                    status: $('#codeDictStatusList').val()
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备参数状态已批量修改", "success");

                        setTimeout(function () {
                            window.location.reload();
                        }, 2000);
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            changeDeviceDataStatus: function (deviceCode, type, self) {
                let isCheck = $(self).is(':checked');

                startLoading();

                $.post('backend/device/changeCodeStatus', {
                    deviceCode: deviceCode,
                    type: type,
                    code: $(self).val(),
                    status: isCheck ? 1 : 0
                }, function (result) {
                    endLoading();

                    if (result.code === 0) {
                        info("设备参数状态变更成功", "success");
                    } else {
                        info(result.msg, "error");
                    }
                });
            },
            changeCodeText: function (deviceCode, type, self) {
                _deviceDataList.v.tempDeviceCode = deviceCode;
                _deviceDataList.v.tempCodeDictCode = $(self).prev().val();
                _deviceDataList.v.tempType = type;

                $('#hiddenCodeInfoDeviceCode').val(deviceCode);
                $('#hiddenCodeInfoType').val(type);
                $('#codeInfoText').val($(self).html());
                _deviceDataList.v.tempCodeDict = $(self).prev().val();

                $('#codeInfoModal').modal('show');
            },
            saveCodeInfo: function () {
                let str = $('#codeInfoText').val();

                if (str.trim().length === 0) {
                    info("字段内容不能为空", "warning");
                    return;
                }

                $.post('backend/device/changeCodeName', {
                    deviceCode: $('#hiddenCodeInfoDeviceCode').val(),
                    type: $('#hiddenCodeInfoType').val(),
                    code: _deviceDataList.v.tempCodeDict,
                    content: str
                }, function (result) {
                    if (result.code === 0) {
                        info("设备参数内容变更成功，刷新界面后可见", "success");
                    } else {
                        info(result.msg, "error");
                    }

                    $('#codeInfoModal').modal('hide');
                });
            },
            loadDeviceEmissionInfo: function () {
                $.post('backend/device/findDeviceEmissionInfo', {
                    deviceCode: $('#hiddenDeviceCode').val()
                }, function (result) {
                    if (result.length > 0) {
                        $('#batchAddTBody').siblings().remove();

                        $.each(result, function (i, item) {
                            _deviceDataList.fn.addNewLine(item.codeName, item.codeCount, item.codeDay);
                        });
                    }
                });
            },
            addNewLine: function (codeName, count, day) {
                let content = '';

                content = '<tr class="batch_Tr">';
                content += '<td><input type="text" maxlength="20" value="' + codeName + '" /></td>';
                content += '<td><input type="number" maxlength="10" value="' + count + '" /></td>';
                content += '<td><input type="number" maxlength="10" onkeyup="_deviceDataList.fn.changeInput(this)" value="' + day + '" /></td>';
                content += '<td><button type="button" class="btn btn-danger btn-sm" onclick="_deviceDataList.fn.delEmissionLine(this)">删除</button></td>';
                content += '</tr>';

                $('#batchAddTBody').after(content);
            },
            delEmissionLine: function (self) {
                $(self).parent().parent().remove();
            },
            changeInput: function (self) {
                $(self).val($(self).val().replace(/\D/g, ''));
            },
            updateStaticCode: function () {
                $("#updateStaticCodeModal").modal("show");
            },
            saveEmissionInfo: function () {
                let codeName = '';
                let count = '';
                let day = '';

                let codeNameStr = '';
                let countStr = '';
                let dayStr = '';

                let flag = true;

                $('.batch_Tr').each(function () {
                    codeName = $(this).children().eq(0).children().eq(0).val();
                    count = $(this).children().eq(1).children(':first').val();
                    day = $(this).children().eq(2).children(':first').val();

                    if (codeName.trim().length === 0) {
                        info('排放因子名称不能为空', "error");
                        flag = false;
                        return;
                    }

                    if (isNaN(count) || Number(count) <= 0) {
                        info('请输入正确的排放因子年排放总量', "error");
                        flag = false;
                        return;
                    }

                    if (isNaN(day) || Number(day) <= 0 || Number(day) > 10000) {
                        info('请输入正确的计算周期', "error");
                        flag = false;
                        return;
                    }

                    codeNameStr += codeName + ",";
                    countStr += count + ",";
                    dayStr += day + ",";
                });

                if (flag && codeNameStr.trim().length > 0 && countStr.trim().length > 0) {
                    startLoading();

                    $.post('backend/device/updateDeviceEmission', {
                        deviceCode: $('#hiddenDeviceCode').val(),
                        codeNameStr: codeNameStr,
                        countStr: countStr,
                        dayStr: dayStr
                    }, function (result) {
                        endLoading();

                        if (result.code === 0) {
                            info("设备排放因子信息修改成功！！", "success");

                            $("#updateStaticCodeModal").modal("hide");
                        } else {
                            info(result.msg, "error");
                        }
                    });
                }
            },
            delInfo: function (id) {
                swal({
                    title: "您确定要删除这条记录吗",
                    text: "删除后将无法恢复，请谨慎操作！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "是的，删除！",
                    cancelButtonText: "不，取消",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        startLoading();

                        $.post('backend/alarmRule/del', {
                            id: id
                        }, function (result) {
                            endLoading();

                            if (result.code === 0) {
                                swal("删除成功！", "您已经删除了这条记录。", "success");

                                _alarmRuleList.fn.reloadData();
                            } else {
                                info(result.msg, "error");
                            }
                        });
                    } else {
                        swal("已取消", "您取消了删除操作！", "error");
                    }
                })
            }
        }
    };

    $(document).ready(function () {
        _deviceDataList.fn.init();

        window.onload = function () {
            checkSelectMenu("deviceLi");

            loadMenuColor('deviceLi');
        }
    });
</script>
</body>
</html>